package com.situ.edu.dao.impl;

import com.situ.edu.dao.IUserDao;
import com.situ.edu.pojo.entity.User;
import com.situ.edu.util.JDBCUtils;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class UserDaoImpl implements IUserDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public User login(String name, String password) {

        try {
            return template.queryForObject("select id,name,password,role,phone,image,status,is_deleted,create_time,update_time from user where name=? and password=?",
                    new BeanPropertyRowMapper<>(User.class), name, password);
        }catch (EmptyResultDataAccessException e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<User> selectAll() {
        return template.query("select * from user", new BeanPropertyRowMapper<>(User.class));
    }

    @Override
    public void updatePass(int id,String newPass) {
        template.update("update user set password=? where id=?",newPass,id);
    }

    @Override
    public User selectById(int id) {
        return template.queryForObject("select * from user where id=?",
                new BeanPropertyRowMapper<>(User.class),id);
    }

    @Override
    public void updatePic(User user) {
        template.update("UPDATE user SET image = ? WHERE id = ?",user.getImage(),user.getId());
    }
}
